package com.huifaapp.mall.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.ApplybankTX;
import com.huifaapp.mall.bean.Fee;
import com.huifaapp.mall.bean.Huishengqian.BankList;
import com.huifaapp.mall.bean.Huishengqian.Banlance;
import com.huifaapp.mall.bean.MineFragmentBean;
import com.huifaapp.mall.dialogs.CustomDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.view.Wuview.WheelView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DepositActivity extends AppCompatActivity {
    private ImageView DiatewxCheeck,DiatezfbCheeck;
    private LinearLayout WxLayout,ZfbLayout;
    private ImageView Imback;
    private EditText ed_phonenum;
    private Button bt_yzm;
    private EditText etAliAccount;
    private EditText etAliName;
    private EditText etAmount;
    private EditText etCode;
    private Button btnTixian;
    private TextView tv_money;
    private  EditText ed_bankname;
    private  EditText ed_bankphonenumber;
    private  EditText ed_banknumber;
    private  TextView  ed_bank;
    private  TextView tv_allmoney;
    private  EditText ed_money;
    private  Button   but_alltixian;

    private String bankname;
    private String number;
    private String banknumeber;
    private String bank;
    private String money;
    private TextView tvclear;
    private  TextView tvok;

    private WheelView w;
    private  PopupWindow window;
    private List<BankList.DataBean> data;
    private String code;//银行code
    private double balance;//余额
    private TextView tvtishi;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit);
        initView();
        initbank();
        getALLBank();//获得银行卡的列表
        getbalance();
        //money的输入监听
        ed_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (!TextUtils.isEmpty(s)){
                        if (Double.parseDouble(s.toString()) > balance) {
                            tvtishi.setText("金额已超过账户余额");
                            tvtishi.setTextColor(getResources().getColor(R.color.red));
//                            but_alltixian.setEnabled(Boolean.FALSE);
                            return;
                        }
                        if (Double.parseDouble(s.toString())<=balance){
                            tvtishi.setText("本次账户内最多可提现金额"+balance+"元");
                            tvtishi.setTextColor(getResources().getColor(R.color.testxiaohui));
                        }

                    }
            }


            @Override
            public void afterTextChanged(Editable s) {

            }
        });



        //bank提现
        but_alltixian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bankname = ed_bankname.getText().toString();
                number = ed_bankphonenumber.getText().toString();
                banknumeber = ed_banknumber.getText().toString();
                bank = ed_bank.getText().toString();
                money = ed_money.getText().toString();

                Log.e("zhuanhua",money);
                Log.e("bankname",bankname);
                Log.e("banknumeber",banknumeber);
                Log.e("code",code);
                Log.e("number",number);
                getTixian(bankname,banknumeber,code,number,money);
            }
        });

        //全部提现
        tv_allmoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ed_money.setText(balance+"");

            }
        });
    }
/*
        bank-list
 */
    private void getALLBank() {
        OkHttpUtils.get().url(ApiManager.BankLIst)
                .build().execute(new StringCallback() {

            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                BankList bankList = new Gson().fromJson(response, BankList.class);
                if (bankList.getCode().equals("10000")){
                    data = bankList.getData();
                }else {
                    Toast.makeText(DepositActivity.this,bankList.getMsg(),Toast.LENGTH_SHORT).show();

                }

            }
        });
    }

    /*
                查询余额

     */
    private void getbalance() {
        OkHttpUtils.post().url(ApiManager.balance)
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(DepositActivity.this))
                .build()
                .execute(new StringCallback() {



                    @Override
                    public void onError(Request request, Exception e) {
                                    Log.e("查询余额",request.urlString());
                                    Log.e("查询余额",e.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        Banlance banlance = new Gson().fromJson(response, Banlance.class);
                        if (banlance.getCode().equals("10000")){

                            balance = banlance.getData().getBalance();
                            Log.e("balance",balance+"");
                            new Handler().post(new Runnable() {
                                @Override
                                public void run() {
                                    tvtishi.setText("本次账户内最多可提现金额"+balance+"元");
                                }
                            });


                        }else {
                            Toast.makeText(DepositActivity.this,banlance.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /*
            申请提现
     */
    public  void  getTixian(String cardName, String cardNo, String bandCode, String phone, final String amount){
                Log.e("cardNo",cardNo);
        Map map = new HashMap();
        map.put("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        map.put("appId",AUniqueIdentifier.getDeviceId(DepositActivity.this));
        map.put("cardName",cardName);
        map.put("cardNo",cardNo);
        map.put("bandCode",bandCode);
        map.put("phone",phone);
        map.put("amount",amount);
       OkHttpUtils.post().url(ApiManager.BankAppley)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.e("提现url",request.urlString());
                      Toast.makeText(DepositActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onResponse(String response) {
                        ApplybankTX applybankTX = new Gson().fromJson(response, ApplybankTX.class);
                        if (applybankTX.getCode().equals("10000")){

                            servicecharge(amount);

                        }else {
                            Toast.makeText(DepositActivity.this,applybankTX.getMsg(),Toast.LENGTH_SHORT).show();
                        }


                    }
                });


    }

        /*
                手续费网络请求
         */
        public  void servicecharge(String money ){
            Map map = new HashMap();
            map.put("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
            map.put("appId",AUniqueIdentifier.getDeviceId(DepositActivity.this));
            map.put("amount",money);
            OkHttpUtils.post().url(ApiManager.FEE)
                    .params(map)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Request request, Exception e) {
                Log.e("手续费",request.urlString());

                }

                @Override
                public void onResponse(String response) {
                    Fee fee = new Gson().fromJson(response, Fee.class);
                    if (fee.getCode().equals("10000")){
                        double amount =  fee.getData().getAmount();
                        double fee1 =  fee.getData().getFee();
                        showdilog(amount,fee1);

                    }else {
                        Toast.makeText(DepositActivity.this,fee.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

        /*
                显示dilog
         */
        private void showdilog(double amount,double fee){
            final CustomDialog dialog = new CustomDialog(this);
            dialog.show();
          //到账余额
         dialog.settvarrivalamount("到账金额:"+amount+"元");
           //到账手续费
          dialog.settvcharge("您本次提现将扣取"+fee+"" +
                  "元手续费，我们会在3个工作日内到账，请您耐心等待～～");
            dialog.setcancelButton(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setaffirmButton(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(DepositActivity.this,"正在开发",Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });
        }

    private void initbank() {
        ed_bankname = (EditText) findViewById(R.id.et_yl_name);

        ed_bankphonenumber = (EditText) findViewById(R.id.number);

        ed_banknumber = (EditText) findViewById(R.id.card_number);

        ed_bank = (TextView) findViewById(R.id.TotheBank);

        tv_allmoney = (TextView) findViewById(R.id.All_withdrawal);
        ed_money = (EditText) findViewById(R.id.money);

        but_alltixian = (Button) findViewById(R.id.but_qurentx);
        tvtishi = (TextView) findViewById(R.id.tv_tishi);
        //选择银行卡
        ed_bank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeKeyboard();//关闭键盘
            List<String> liststr = new ArrayList<>();
                int size = data.size();
                for (int i = 0; i <size ; i++) {
                    BankList.DataBean dataBean = data.get(i);
                    String name = dataBean.getName();
                    liststr.add(name);
                }
                // 构建弹出框View
                View outerView = LayoutInflater.from(DepositActivity.this)
                        .inflate(R.layout.activity_wheel_view, null);
                w = (WheelView) outerView.findViewById(R.id.wheelview);
                tvclear = (TextView) outerView.findViewById(R.id.cleaer);
                tvok = (TextView) outerView.findViewById(R.id.ok);
                //设置偏移量
                w.setOffset(2);
                //设置条目
                w.setItems(liststr);
                w.setSeletion(0);
                window = new PopupWindow(outerView, RelativeLayout.LayoutParams.MATCH_PARENT,800,true );
                window.setOutsideTouchable(true);
                window.setTouchable(true);
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.7f;
                getWindow().setAttributes(lp);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 1f;
                        getWindow().setAttributes(lp);
                    }
                });
                window.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM , 0, 0);
                tvclear.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();
                    }
                });
                tvok.setOnClickListener(new View.OnClickListener() {



                    @Override
                    public void onClick(View v) {
                        String seletedItem = w.getSeletedItem();
                        int seletedIndex = w.getSeletedIndex();
                        Log.e("seletedItem",seletedItem);
                        Log.e("seletedIndex",seletedIndex+"");
                        ed_bank.setText(seletedItem);
                        code = data.get(seletedIndex).getCode();
                        window.dismiss();
                    }
                });

            }
        });




    }

    private void initView() {
        DiatewxCheeck = (ImageView) findViewById(R.id.diatewxcheck);
        DiatezfbCheeck = (ImageView) findViewById(R.id.diatezfbcheck);
        WxLayout = (LinearLayout) findViewById(R.id.onebuju);
        ZfbLayout = (LinearLayout) findViewById(R.id.twobuju);
        Imback = (ImageView) findViewById(R.id.iv_deposit_back);
        bt_yzm = (Button) findViewById(R.id.deposit_btyzm);
        btnTixian = (Button) findViewById(R.id.btn_tixian);
        tv_money = (TextView) findViewById(R.id.deposit_keyongyue);

        ed_phonenum = (EditText) findViewById(R.id.deposit_phone);
        etAliAccount = (EditText) findViewById(R.id.et_ali_account);
        etAliName = (EditText) findViewById(R.id.et_ali_name);
        etAmount = (EditText) findViewById(R.id.et_amount);
        etCode = (EditText) findViewById(R.id.et_code);
        DiatezfbCheeck.setImageResource(R.drawable.porfile_icon_set_sel);
        DiatewxCheeck.setImageResource(R.drawable.porfile_icon_set_nor);
        ZfbLayout.setVisibility(View.VISIBLE);
        WxLayout.setVisibility(View.GONE);
        DiatewxCheeck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DiatewxCheeck.setImageResource(R.drawable.porfile_icon_set_sel);
                DiatezfbCheeck.setImageResource(R.drawable.porfile_icon_set_nor);
                WxLayout.setVisibility(View.VISIBLE);
                ZfbLayout.setVisibility(View.GONE);
            }
        });
        DiatezfbCheeck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DiatezfbCheeck.setImageResource(R.drawable.porfile_icon_set_sel);
                DiatewxCheeck.setImageResource(R.drawable.porfile_icon_set_nor);
                ZfbLayout.setVisibility(View.VISIBLE);
                WxLayout.setVisibility(View.GONE);
            }
        });

        Imback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"users/index")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(DepositActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                    }

                    @Override
                    public void onResponse(String response) {
                        Gson gson= new Gson();
                        MineFragmentBean mineFragmentBean= gson.fromJson(response,MineFragmentBean.class);
                        tv_money.setText(mineFragmentBean.getUserinfo().getMoney()+"元");
                    }
                });



        bt_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = ed_phonenum.getText().toString();
                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+""+"login/code")
                        .addParams("phone",phone)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {

                            }

                            @Override
                            public void onResponse(String response) {

                                CountDownTimer timer = new CountDownTimer(60000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        bt_yzm.setEnabled(false);
                                        bt_yzm.setText("已发送(" + millisUntilFinished / 1000 + ")");

                                    }

                                    @Override
                                    public void onFinish() {
                                        bt_yzm.setEnabled(true);
                                        bt_yzm.setText("重新获取验证码");

                                    }
                                }.start();


                            }
                        });

            }
        });
        btnTixian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phontNum = getInput(ed_phonenum);
                String aliAccount = getInput(etAliAccount);
                String aliName = getInput(etAliName);
                String amount = getInput(etAmount);
                String code = getInput(etCode);
                if (inputEmpty(phontNum,aliAccount,aliName,amount,code)){
                    showToast("请输入相应信息");
                    return;
                }
                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"withDrawals/ali/apply")
                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                        .addParams("appId", AUniqueIdentifier.getDeviceId(DepositActivity.this))
                        .addParams("aliName",aliName)
                        .addParams("aliAccount",aliAccount)
                        .addParams("phone",phontNum)
                        .addParams("code",code)
                        .addParams("amount",amount)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {

                            }

                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject object=new JSONObject(response);
                                    if(object.getString("code").equals("10000")){
                                        ToastUtils.showShort("提现成功");
                                    }else {
                                        Toast.makeText(DepositActivity.this,object.getString("msg"),Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });
            }
        });

    }
    private String getInput(EditText et){
        return et.getText().toString().trim();
    }
    private boolean inputEmpty(String arg0,String arg1,String arg2,String arg3,String arg4){
        if (TextUtils.isEmpty(arg0)||TextUtils.isEmpty(arg1)||TextUtils.isEmpty(arg2)||TextUtils.isEmpty(arg3)||TextUtils.isEmpty(arg4)){
            return true;
        }else{
            return false;
        }
    }
    private void showToast(String msg){
        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
    }

    private void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
